package com.hulk.rpc.transport.server.rpc.codec;

import com.hulk.rpc.protocol.Response;
import com.hulk.rpc.serialize.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author xuxukang
 */
@Slf4j
public class ResponseEncoder extends MessageToByteEncoder<Response> {
  private final Serializer serializer;

  public ResponseEncoder(Serializer serializer) {
    this.serializer = serializer;
  }

  @Override
  protected void encode(ChannelHandlerContext ctx, Response response, ByteBuf buffer) throws Exception {
    serializer.writeResponse(buffer, response);
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (log.isErrorEnabled()) {
      log.error("Exception caught on " + ctx.channel(), cause);
    }

    ctx.channel().close();
  }

}
